package com.fast.alden.data.aspect;

import com.fast.alden.data.model.BaseEntity;
import com.fast.alden.data.model.BaseUser;
import com.fast.alden.data.model.PortalUser;
import com.fast.alden.data.model.SysUser;
import com.fast.alden.data.service.CurrentPortalUserService;
import com.fast.alden.data.service.CurrentSysUserService;
import jakarta.persistence.PrePersist;
import jakarta.persistence.PreUpdate;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 监听insert和update，执行前使用当前用户为相关属性赋值
 */
public class BaseEntityAuditingListener {
    @Autowired(required = false)
    private CurrentSysUserService currentSysUserService;
    @Autowired(required = false)
    private CurrentPortalUserService currentPortalUserService;

    @PrePersist
    private void prePersist(BaseEntity entity) {
        BaseUser current = getCurrent();

        setCreator(entity, current);
        setLastModifier(entity, current);
    }

    @PreUpdate
    private void preUpdate(BaseEntity entity) {
        BaseUser current = getCurrent();

        setLastModifier(entity, current);
    }

    private BaseUser getCurrent() {
        PortalUser portalUser = currentPortalUserService != null ? currentPortalUserService.currentUser() : null;
        SysUser sysUser = currentSysUserService != null ? currentSysUserService.currentUser() : null;

        BaseUser current = null;
        if (portalUser != null && sysUser == null) {
            current = portalUser;
        } else if (portalUser == null && sysUser != null) {
            current = sysUser;
        }

        return current;
    }

    private void setCreator(BaseEntity entity, BaseUser current) {
        if (current != null) {
            // 0-后台用户，1-前台用户
            Integer userType = current instanceof PortalUser ? 1 : 0;
            entity.setCreatorId(current.getId());
            entity.setCreatorName(current.getNickname());
            entity.setCreatorType(userType);
        }
    }

    private void setLastModifier(BaseEntity entity, BaseUser current) {
        if (current != null) {
            // 0-后台用户，1-前台用户
            Integer userType = current instanceof PortalUser ? 1 : 0;
            entity.setLastModifierId(current.getId());
            entity.setLastModifierName(current.getNickname());
            entity.setLastModifierType(userType);
        }
    }
}
